<template>
  <div class="propertyAcceptancePage d-flex">
    <div
      class="d-flex flex-column"
      v-if="
        acceptanceStatus == 1 || acceptanceStatus == 2 || acceptanceStatus == 3
      "
    >
      <div v-if="html">
        <div>
          <h3>
            物业审核状态: {{ ['', '待审批', '通过', '驳回'][acceptanceStatus] }}
          </h3>
        </div>
        <div class="flex-1" v-html="html"></div>
        <div class="attachment-wrap" v-if="adjunctUrl.length > 1">
          <div style="margin-top: -85px; margin-left: 120px">
            <span>查看附件</span>
            <el-button
              @click="downloadFile"
              class="button_view"
              style="margin-left: 10px"
              >请下载附件</el-button
            >
          </div>
        </div>
        <div class="button-wrap d-flex a-center j-center">
          <el-button @click="clickhHandle" class="button_edit">重新填写验收信息</el-button>
        </div>
      </div>
    </div>

    <div v-if="acceptanceStatus == 0" class="page-content d-flex">
      <div v-html="html" class="html-box"></div>
      <div
        :class="[
          rightBoxState.hideRightBoxFlag
            ? 'form-wrap hide-width'
            : 'form-wrap show-width'
        ]"
      >
        <div
          class="ctrlBtnBox"
          :class="rightBoxState.hideRightBoxFlag ? 'toLeftBtn' : 'toLeftBtn'"
          @click="doControlRight"
        >
          <el-icon :size="20" v-if="!rightBoxState.hideRightBoxFlag"
            ><ArrowRight
          /></el-icon>
          <el-icon :size="20" v-else><ArrowLeft /></el-icon>
        </div>
        <div class="form-box">
          <el-form
            label-width="140px"
            :model="form"
            ref="ruleFormRef"
            :rules="rules"
          >
            <el-form-item label="清场日期" prop="clearanceTime">
              <el-date-picker
                v-model="form.clearanceTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择清场日期"
              />
            </el-form-item>
            <el-form-item label="室内装修有无破坏" prop="decorationType">
              <el-radio-group class="radio-group" v-model="form.decorationType">
                <el-radio :label="1">
                  <div class="d-flex">
                    <span style="margin: 0 5px">有</span>
                    <el-input
                      :disabled="form.decorationType === 2"
                      v-model="form.decorationMoney"
                      placeholder="请输入金额"
                      @input="
                        form.decorationMoney = limitInputNum(
                          form.decorationMoney,
                          5,
                          2
                        )
                      "
                      @blur="
                        form.decorationMoney = filterInputNum(
                          form.decorationMoney
                        )
                      "
                    ></el-input>
                  </div>
                </el-radio>
                <el-radio :label="2">
                  <div class="d-flex a-center">
                    <span style="margin: 0 5px">无</span>
                    <el-input
                      :disabled="form.decorationType === 1"
                      v-model="form.decorationRemarks"
                      placeholder="请输入备注"
                    ></el-input>
                  </div>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="机电设备有无短缺"
              required
              prop="damagedEquipmentType"
            >
              <el-radio-group
                class="radio-group"
                v-model="form.damagedEquipmentType"
              >
                <el-radio :label="1">
                  <div class="d-flex">
                    <span style="margin: 0 5px">有</span>
                    <el-input
                      :disabled="form.damagedEquipmentType === 2"
                      v-model="form.damagedEquipmentMoney"
                      placeholder="请输入金额"
                      @input="
                        form.damagedEquipmentMoney = limitInputNum(
                          form.damagedEquipmentMoney,
                          5,
                          2
                        )
                      "
                      @blur="
                        form.damagedEquipmentMoney = filterInputNum(
                          form.damagedEquipmentMoney
                        )
                      "
                    ></el-input>
                  </div>
                </el-radio>
                <el-radio :label="2">
                  <div class="d-flex a-center">
                    <span style="margin: 0 5px">无</span>
                    <el-input
                      :disabled="form.damagedEquipmentType === 1"
                      v-model="form.equipmentRemarks"
                      placeholder="请输入备注"
                    ></el-input>
                  </div>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="正式断电日期">
              <el-date-picker
                v-model="form.interruptTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择正式断电日期"
              />
            </el-form-item>
            <el-form-item label="电表度数">
              <el-input
                v-model="form.electricityNum"
                placeholder="请输入电表度数"
                @input="
                  form.electricityNum = limitInputNum(
                    form.electricityNum,
                    5,
                    0,
                    false
                  )
                "
              ></el-input>
            </el-form-item>
            <el-form-item label="电表号">
              <el-input
                v-model="form.electricityNumber"
                placeholder="请输入电表号"
              ></el-input>
            </el-form-item>
            <el-form-item label="交还钥匙">
              <div class="d-flex">
                <el-input
                  v-model="form.keysNum"
                  placeholder="交还钥匙数"
                  @input="
                    form.keysNum = limitInputNum(form.keysNum, 4, 0, false)
                  "
                ></el-input>
                <span style="margin-left: 5px">把</span>
              </div>
            </el-form-item>
            <el-form-item
              label="管理费缴付情况"
              required
              prop="managementExpenseType"
            >
              <el-radio-group
                class="radio-group"
                v-model="form.managementExpenseType"
              >
                <el-radio :label="1">
                  <span style="margin: 0 5px">已缴清</span>
                </el-radio>
                <el-radio :label="2">
                  <div class="d-flex a-center">
                    <span style="margin: 0 5px">未缴清</span>
                    <el-input
                      :disabled="form.managementExpenseType === 1"
                      style="width: 50%"
                      v-model="form.managementExpenseMoney"
                      placeholder="请输入金额"
                      @input="
                        form.managementExpenseMoney = limitInputNum(
                          form.managementExpenseMoney,
                          5,
                          2
                        )
                      "
                      @blur="
                        form.managementExpenseMoney = filterInputNum(
                          form.managementExpenseMoney
                        )
                      "
                    ></el-input>
                  </div>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="水电缴付情况"
              required
              prop="waterAndElectricityType"
            >
              <el-radio-group
                class="radio-group"
                v-model="form.waterAndElectricityType"
              >
                <el-radio :label="1">
                  <span style="margin: 0 5px">已缴清</span>
                </el-radio>
                <el-radio :label="2">
                  <div class="d-flex a-center">
                    <span style="margin: 0 5px">未缴清</span>
                    <el-input
                      :disabled="form.waterAndElectricityType === 1"
                      style="width: 50%"
                      v-model="form.waterAndElectricityMoney"
                      placeholder="请输入金额"
                      @input="
                        form.waterAndElectricityMoney = limitInputNum(
                          form.waterAndElectricityMoney,
                          5,
                          2
                        )
                      "
                      @blur="
                        form.waterAndElectricityMoney = filterInputNum(
                          form.waterAndElectricityMoney
                        )
                      "
                    ></el-input>
                  </div>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="其他事宜">
              <el-input
                type="textarea"
                :rows="3"
                v-model="form.other"
                placeholder="清输入事宜"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="是否拖欠管理费"
              required
              prop="behindManagementType"
            >
              <el-radio-group
                class="radio-group"
                v-model="form.behindManagementType"
              >
                <el-radio :label="1">
                  <div class="d-flex">
                    <span style="margin: 0 5px">有</span>
                    <el-input
                      :disabled="form.behindManagementType === 2"
                      v-model="form.behindManagementMoney"
                      placeholder="请输入金额"
                      @input="
                        form.behindManagementMoney = limitInputNum(
                          form.behindManagementMoney,
                          5,
                          2
                        )
                      "
                      @blur="
                        form.behindManagementMoney = filterInputNum(
                          form.behindManagementMoney
                        )
                      "
                    ></el-input>
                  </div>
                </el-radio>
                <el-radio :label="2">
                  <div class="d-flex a-center">
                    <span style="margin: 0 5px">无</span>
                    <el-input
                      :disabled="form.behindManagementType === 1"
                      v-model="form.behindManagementRemarks"
                      placeholder="请输入备注"
                    ></el-input>
                  </div>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="是否拖欠房租"
              required
              prop="behindRentType"
            >
              <el-radio-group class="radio-group" v-model="form.behindRentType">
                <el-radio :label="1">
                  <div class="d-flex">
                    <span style="margin: 0 5px">有</span>
                    <el-input
                      :disabled="form.behindRentType === 2"
                      v-model="form.behindRentMoney"
                      placeholder="请输入金额"
                      @input="
                        form.behindRentMoney = limitInputNum(
                          form.behindRentMoney,
                          5,
                          2
                        )
                      "
                      @blur="
                        form.behindRentMoney = filterInputNum(
                          form.behindRentMoney
                        )
                      "
                    ></el-input>
                  </div>
                </el-radio>
                <el-radio :label="2">
                  <div class="d-flex a-center">
                    <span style="margin: 0 5px">无</span>
                    <el-input
                      :disabled="form.behindRentType === 1"
                      v-model="form.behindRentRemarks"
                      placeholder="请输入备注"
                    ></el-input>
                  </div>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="上传附件">
              <el-upload
                ref="upload"
                class="upload-demo"
                :limit="1"
                :http-request="uploadFile"
                @on-remove="onRemove"
              >
                <template #trigger>
                  <el-button class="button_view">选择文件</el-button>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
        <div
          v-if="!rightBoxState.hideRightBoxFlag"
          class="button-wrap d-flex a-center j-center"
        >
          <el-button @click="onPreview" class="button_edit">预览</el-button>
          <el-button @click="onSubmit" class="button_view">提交审批</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, watch} from 'vue'
import { useRouter } from 'vue-router'
import { leaseApi, otherApi } from '@/api/lease'
import { ArrowRight, ArrowLeft } from '@element-plus/icons-vue'
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElDatePicker,
  ElUpload,
  ElMessage,
  ElMessageBox
} from 'element-plus'
import { limitInputNum, filterInputNum } from '@/common/utils/GlobalUtils'
import store from "@/store";
import {clearCache} from "@/utils/createRoutes";

const router = useRouter()
const contractId = router.currentRoute.value.params.contractId
// 物业审核状态 0  1:待审核 2:通过 3:驳回
const acceptanceStatus = ref(router.currentRoute.value.params.acceptanceStatus)
const convert = (url) => {
  return url.replaceAll('@', '/')
}
// 下载文件链接
let adjunctUrl = convert(router.currentRoute.value.params.adjunctUrl)
const html = ref('')

const form = reactive({
  clearanceTime: '', // 清场日期
  decorationType: 1, //室内装修有无破坏 1:有 2:无
  decorationMoney: '', // 室内装修破坏的金额
  decorationRemarks: '', // 室内装修破坏的备注
  damagedEquipmentType: 1, // 机电设备有无短缺 1:有 2:无
  damagedEquipmentMoney: '', // 机电设备破坏的金额
  equipmentRemarks: '', // 机电破坏的备注
  interruptTime: '', // 断电日期
  electricityNum: '', // 电表度数
  electricityNumber: '', // 电表号
  keysNum: '', // 钥匙数量
  managementExpenseType: 1, // 管理费缴付情况 1:已缴清 2:未缴清
  managementExpenseMoney: '', // 管理费未缴清的金额
  waterAndElectricityType: 1, // 水电费是否缴清 1:已缴清 2:未缴清
  waterAndElectricityMoney: '', // 水电费未缴清金额
  other: '', // 其他事宜
  behindManagementType: 1, // 是否有拖欠管理费 1:有 2:无
  behindManagementMoney: '', // 拖欠管理费的金额
  behindManagementRemarks: '', // 拖欠管理费的备注
  behindRentType: 1, // 是否拖欠房租 1:是 2:否
  behindRentMoney: '', // 拖欠房租的金额
  behindRentRemarks: '', // 拖欠房租的备注
  urlKey: '', // 文件链接
  fileName:''
})

// 室内装修有无破坏 验证
const decorationTypeValidatePass = (rule, value, callback) => {
  if (value === 1 && form.decorationMoney === '') {
    return callback(new Error('室内装修破坏的金额不能为空'))
  }

  callback()
}

// 机电设备有无短缺 验证
const damagedEquipmentTypeValidatePass = (rule, value, callback) => {
  if (value === 1 && form.damagedEquipmentMoney === '') {
    return callback(new Error('机电设备有无短缺的金额不能为空'))
  }

  callback()
}

// 管理费缴付情况
const managementExpenseTypeValidatePass = (rule, value, callback) => {
  if (value === 2 && form.managementExpenseMoney === '') {
    return callback(new Error('管理费未缴金额不能为空!'))
  }
  callback()
}

// 水电费是否缴清 验证
const waterAndElectricityTypeValidatePass = (rule, value, callback) => {
  if (value === 2 && form.waterAndElectricityMoney === '') {
    return callback(new Error('水电费未缴金额不能为空!'))
  }
  callback()
}

// 是否拖欠管理费 验证
const behindManagementTypeValidatePass = (rule, value, callback) => {
  if (value === 1 && form.behindManagementMoney === '') {
    return callback(new Error('拖欠管理费金额不能为空'))
  }

  callback()
}

// 拖欠房租 验证
const behindRentTypeValidatePass = (rule, value, callback) => {
  if (value === 1 && form.behindRentMoney === '') {
    return callback(new Error('拖欠房租的金额不能为空'))
  }
 
  callback()
}
//获取当前时间YYYY-MM-DD
const getNowFormatDate = () => {
  const date = new Date()
  const seperator1 = '-'
  const year = date.getFullYear()
  let month = date.getMonth() + 1
  let strDate = date.getDate()
  if (month >= 1 && month <= 9) {
    month = '0' + month
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = '0' + strDate
  }
  const currentdate = year + seperator1 + month + seperator1 + strDate
  return currentdate
}
//判断当前日期是否等于清场日期
const isClearanceTime = (rule, value, callback) => {
  if (value === getNowFormatDate()) {
    return callback(new Error('清场日期不能等于当前日期'))
  }
  callback()
}
const rules = reactive({
  clearanceTime: [
    { required: true, message: '请选择清场日期', trigger: 'change' },
    { validator: isClearanceTime, trigger: 'change' }
  ],
  decorationType: [{ validator: decorationTypeValidatePass, trigger: 'blur' }],
  damagedEquipmentType: [
    { validator: damagedEquipmentTypeValidatePass, trigger: 'blur' }
  ],
  managementExpenseType: [
    { validator: managementExpenseTypeValidatePass, trigger: 'blur' }
  ],
  waterAndElectricityType: [
    { validator: waterAndElectricityTypeValidatePass, trigger: 'blur' }
  ],
  behindManagementType: [
    { validator: behindManagementTypeValidatePass, trigger: 'blur' }
  ],
  behindRentType: [{ validator: behindRentTypeValidatePass, trigger: 'blur' }]
})

// 获取合同
const getPropertyTerminationAgreement = () => {
  leaseApi
    .getPropertyTerminationAgreement({
      contractId: contractId,
      templateUrlKey: '物业验收协议01.docx'
    })
    .then((res) => {
      html.value = res
    })
}

// 收起/展开 相关
const rightBoxState = reactive({
  hideRightBoxFlag: false, // 控制右侧整体
  hideRightCnFlag: false // 控制右侧内容部分
})

// 收起/展开按钮点击
const doControlRight = () => {
  rightBoxState.hideRightBoxFlag = !rightBoxState.hideRightBoxFlag
  if (rightBoxState.hideRightBoxFlag) {
    // 收起时
    setTimeout(() => {
      // 延时控制，解决收起时横向滚动条闪现问题
      rightBoxState.hideRightCnFlag = true
    }, 200)
  } else {
    // 展开时
    setTimeout(() => {
      // 延时控制，解决展开时横向滚动条闪现问题
      rightBoxState.hideRightCnFlag = false
    }, 200)
  }
}

// el-upload 选择文件后
const uploadFile = (file) => {
  let uploadFile = new FormData()
  uploadFile.append('file', file.file)
  otherApi.uploadFile(uploadFile).then((res) => {
    if (res.code === '200') {
      ElMessage.success('上传成功!')
      form.urlKey = res.data
      form.fileName = file.file.name;
    }
  })
}

/**
 * 移除文件
 */
const onRemove = () => {
    form.urlKey = '';
    form.fileName = '';
}

// 预览合同
const onPreview = () => {
  leaseApi
    .preview({
      contractId: contractId,
      templateUrlKey: '物业验收协议01.docx',
      data: form
    })
    .then((res) => {
      if (typeof res === 'string') {
        html.value = res
      } else {
        ElMessageBox.alert('预览失败!请完善表单内容!', {
          confirmButtonText: 'OK'
        })
      }
    })
}

// 提交审核
const ruleFormRef = ref(null)
const onSubmit = () => {
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      let params = {
        contractId: contractId,
        data: form
      }
      leaseApi.submitForReview(params).then((res) => {
        if (res.code == 200) {
          ElMessage.success('提交成功!')
          router.push({ path: '/asset/management/managementIndex', query: {} })
          clearCache({title:'物业验收'});
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 重新编写合同
const clickhHandle = () => {
  acceptanceStatus.value = 0
}

// 下载附件
const downloadFile = () => {
  otherApi
    .downloadFile({
      urlKey: adjunctUrl
    })
    .then((res) => {
      const blob = new Blob([res])
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) //创建下载的链接
      downloadElement.href = href
      downloadElement.download = '附件.png' //下载后文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() //点击下载
      document.body.removeChild(downloadElement) //下载完成移除元素
      window.URL.revokeObjectURL(href) //释放掉blob对象
    })
}

watch(form,(value)=>{
    store.commit("setPropertyAcceptanceForm", form);
},{deep:true});

/**
 * 从vuex中取出数据填充表单
 */
const initForm = () => {
    if (store.state.collaborativeApproval.propertyAcceptanceForm) {
        for (let key in store.state.collaborativeApproval.propertyAcceptanceForm) {
            for (let key2 in form) {
                form[key] = store.state.collaborativeApproval.propertyAcceptanceForm[key];
            }
        }

    }
};


onMounted(() => {
  getPropertyTerminationAgreement();
  initForm();
})
</script>

<style lang="scss" scoped>
.radio-group {
  :deep(.el-radio) {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }
}

.propertyAcceptancePage {
  .page-content {
    width: 100%;
    height: 100%;

    .hide-width {
      flex: none !important;
      transition: all 0.6s;
      padding-right: 20px;
      width: 0px !important;
      overflow-x: hidden;
    }
    .show-width {
      flex: 1;
      transition: all 0.6s;
    }

    .html-box {
      border: 1px solid #e3e7f1;
      border-radius: 10px;
      padding: 36px 120px 30px;
      overflow-x: hidden;
      overflow-y: auto;
      margin-right: 20px;
      flex: 3;
    }
    .form-wrap {
      flex: 1;
      border-left: 5px solid $title-sm-color;
      border-radius: 10px;
      padding: 30px 0 30px 40px;
      position: relative;
      .ctrlBtnBox {
        width: 34px;
        height: 86px;
        line-height: 94px;
        text-align: center;
        padding-left: 10px;
        background: url('@/assets/iconImg/arrowbox.png') no-repeat;
        background-size: cover;
        position: absolute;
        top: 290px;
        cursor: pointer;
      }
      .toLeftBtn {
        left: 14px;
      }
      .form-box {
        margin-left: 20px;
        .showRightWidth {
          width: 428px;
          transition: all 0.6s;
        }
        .hideRightWidth {
          width: 0px;
          padding-left: 0;
          border-left: none;
          transition: all 0.6s;
        }
      }
    }
  }
}
</style>
